
/**
 * 懒加载图片
 * 
 * 使用: 
 *  1.import Lazyloader from '@/utils/lazyloader'
 *  2.new Lazyloader('img[lazy="loaded"]');
 */
class Lazyloader {
    constructor(options) {
        let el = options.el || 'img[lazy="loaded"]';
        let advance = options.advance || 0;
        advance += 'px';
        let opt = {
            rootMargin:'0px 0px '+advance+' 0px'
        };
        this.lazyloadItems = document.querySelectorAll(el);
        this.io = new IntersectionObserver(this.handle,opt);
        this.startObserve();
    }
    handle(entries) {
        for(let i = 0; i < entries.length;i++) {
            if (entries[i].isIntersecting) {
                let item = entries[i].target;
                if(item.getAttribute('src') || !item.getAttribute('data-src')) {
                    return;
                }
                item.setAttribute('src', item.getAttribute('data-src'));
            };
        }
    }
    startObserve() {
        for (let i = 0; i < this.lazyloadItems.length;i++) {
            let item = this.lazyloadItems[i];
            if(!item.getAttribute('src')) {
                this.io.observe(item);
            }
        }
    }
}

export default Lazyloader;